import javax.jms.*;
import org.apache.activemq.ActiveMQConnectionFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class analyseConsumer{
    private static String brokerURL = "tcp://localhost:61616";
    private static ConnectionFactory factory;
    private Connection connection;
    private Session session;
    private MessageProducer producer;
    private Topic topic;
    private MessageConsumer messageConsumer;
    private signalListen listener;

    //作为消费者，传入一个参数
    public analyseConsumer(String topicName) throws JMSException {
        factory = new ActiveMQConnectionFactory(brokerURL);
        connection = factory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        topic = session.createTopic(topicName);
        messageConsumer = session.createConsumer(topic);
        connection.start();
        listener = new signalListen();
        messageConsumer.setMessageListener(listener);
    }

    //作为生产者，传入两个参数
    public analyseConsumer(int a,String topicName) throws JMSException {
        factory = new ActiveMQConnectionFactory(brokerURL);
        connection = factory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        topic = session.createTopic(topicName);
        producer = session.createProducer(topic);
        connection.start();
    }

    //发送分析结果：最小值，最大值，平均值，方差
    public void sendMessage(double minNum,double maxNum,double mean,double variance) throws JMSException {
        StreamMessage message = session.createStreamMessage();
        message.writeDouble(minNum);
        message.writeDouble(maxNum);
        message.writeDouble(mean);
        message.writeDouble(variance);
        producer.send(message);

        System.out.println("发送的随机信号分析结果: "+"最小值 "+minNum+"  最大值 "+maxNum+"  平均值 "+mean+"  方差 "+variance+"\n");
    }

    public void close() throws JMSException {
        if (connection != null) {
            connection.close();
        }
        if (session!=null){
            session.close();
        }
    }

    public static void main(String[] args) throws JMSException {
        analyseConsumer consumer = new analyseConsumer("randomSignal");
        try{
            System.out.println("Press any key to 结束 随机信号分析节点");
            System.in.read();   // Pause
        }catch (Exception e){
            ;
        }
        consumer.close();
    }
}

